package cn.net.dpi.shp.service;

import cn.hutool.core.util.StrUtil;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.linuxense.javadbf.DBFException;
import com.linuxense.javadbf.DBFReader;
import com.linuxense.javadbf.DBFRow;
import com.linuxense.javadbf.DBFUtils;


public interface ShapefileService {

    String SHP_DEFAULT_GEM_NAME = "theGeom";
    boolean ENALE_DEBUG_LOG = false;
    Logger shp_logger = LoggerFactory.getLogger(ShapefileService.class);
    Integer EPSG_4326 = 4326;

    /**
     * 解析shp文件
     *
     * @param baseName 类型名，例如:hd_arrow
     * @param filePath 文件全路径
     * @return
     */
    boolean parseShpfile(Long fileId, String baseName, String filePath, String version, Integer versionFlag, String area);

    default List<Map> defaultParseShpfile1(String filePath) {
        List<Map> list = new ArrayList<>();
        try {
            File file = new File(filePath);
            FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
            SimpleFeatureSource featureSource = dataStore.getFeatureSource();
            SimpleFeatureType schema = featureSource.getSchema();
            if (ENALE_DEBUG_LOG) {
                System.out.println("Feature Type Name: " + schema.getTypeName());
                System.out.println("Number of Attributes: " + schema.getAttributeCount());
                System.out.println("Attribute Descriptors:  " + schema.getAttributeDescriptors().stream().map(AttributeDescriptor::getLocalName).collect(Collectors.joining(",")));
            }
            //检查下坐标系
            CoordinateReferenceSystem sourceCRS = schema.getCoordinateReferenceSystem();
            Integer epsgCode = CRS.lookupEpsgCode(sourceCRS, true);
            shp_logger.info("Source shp EPSG:{}", epsgCode);
            boolean isEpsg4326 = true;
            MathTransform transform = null;
            if (!ObjectUtils.isEmpty(epsgCode) && EPSG_4326.intValue() != epsgCode) {
                shp_logger.info("Source shp EPSG WKT:{} \nwill transform to EPSG code:{}", sourceCRS.toWKT(), EPSG_4326);
                CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + EPSG_4326, true);
                transform = CRS.findMathTransform(sourceCRS, targetCRS);
                isEpsg4326 = false;
            }

            FeatureCollection<SimpleFeatureType, SimpleFeature> collection = featureSource.getFeatures();
            FeatureIterator<SimpleFeature> iterator = collection.features();
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                if (!isEpsg4326) {
                    Geometry geometry = (Geometry) feature.getDefaultGeometry();
                    if (geometry != null) {
                        Geometry transformedGeometry = JTS.transform(geometry, transform);
                        feature.setDefaultGeometry(transformedGeometry);
                    }
                }

                Map map = new HashMap<>();
                for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
                    String camelCase = StrUtil.toCamelCase(ad.getName().toString());
                    map.put(camelCase, feature.getAttribute(ad.getName()));
                    if (ENALE_DEBUG_LOG) {
                        System.out.println("name Attribute " + ad.getName() + "-->" + camelCase + " : " + feature.getAttribute(ad.getName()));
                    }
                }
                list.add(map);
            }
            iterator.close();
        } catch (IOException | FactoryException | TransformException e) {
            shp_logger.error("process shp error:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        return list;
    }

    default List<Map> defaultParseShpfile(String filePath) {
        List<Map> list = new ArrayList<>();
        FeatureIterator<SimpleFeature> iterator = null;
        try {
            File file = new File(filePath);
            String fileExtension = getFileExtension(file.getName());

            if ("shp".equalsIgnoreCase(fileExtension)) {
                // 处理 .shp 文件
                FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
                SimpleFeatureSource featureSource = dataStore.getFeatureSource();
                SimpleFeatureType schema = featureSource.getSchema();

                if (ENALE_DEBUG_LOG) {
                    System.out.println("Feature Type Name: " + schema.getTypeName());
                    System.out.println("Number of Attributes: " + schema.getAttributeCount());
                    System.out.println("Attribute Descriptors:  " + schema.getAttributeDescriptors().stream().map(AttributeDescriptor::getLocalName).collect(Collectors.joining(",")));
                }

                // 检查坐标系
                CoordinateReferenceSystem sourceCRS = schema.getCoordinateReferenceSystem();
                Integer epsgCode = null;
                if(sourceCRS != null) {
                    epsgCode = CRS.lookupEpsgCode(sourceCRS, true);
                    shp_logger.info("Source shp EPSG:{}", epsgCode);
                }
                boolean isEpsg4326 = true;
                MathTransform transform = null;
                if (!ObjectUtils.isEmpty(epsgCode) && EPSG_4326.intValue() != epsgCode) {
                    shp_logger.info("Source shp EPSG WKT:{} \nwill transform to EPSG code:{}", sourceCRS.toWKT(), EPSG_4326);
                    CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + EPSG_4326, true);
                    transform = CRS.findMathTransform(sourceCRS, targetCRS);
                    isEpsg4326 = false;
                }

                SimpleFeatureCollection collection = featureSource.getFeatures();
                iterator = collection.features();
                while (iterator.hasNext()) {
                    SimpleFeature feature = iterator.next();
                    if (!isEpsg4326) {
                        org.locationtech.jts.geom.Geometry geometry = (org.locationtech.jts.geom.Geometry) feature.getDefaultGeometry();
                        if (geometry != null) {
                            org.locationtech.jts.geom.Geometry transformedGeometry = JTS.transform(geometry, transform);
                            feature.setDefaultGeometry(transformedGeometry);
                        }
                    }

                    Map<String, Object> map = new HashMap<>();
                    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
                        String camelCase = StrUtil.toCamelCase(ad.getName().toString());
                        map.put(camelCase, feature.getAttribute(ad.getName()));
                        if (ENALE_DEBUG_LOG) {
                            System.out.println("name Attribute " + ad.getName() + "-->" + camelCase + " : " + feature.getAttribute(ad.getName()));
                        }
                    }
                    list.add(map);
                }
            } else if ("dbf".equalsIgnoreCase(fileExtension)) {
                // 处理 .dbf 文件
                FileInputStream fis = null;
                DBFReader reader = null;
                try {
                    fis = new FileInputStream(filePath);
                    reader = new DBFReader(fis);
                    int fieldCount = reader.getFieldCount();
                    String[] fieldNames = new String[fieldCount];
                    for (int i = 0; i < fieldCount; i++) {
                        fieldNames[i] = reader.getField(i).getName();
                    }

                    DBFRow row;
                    while ((row = reader.nextRow()) != null) {
                        Map<String, Object> rowMap = new HashMap<>();
                        for (int i = 0; i < fieldCount; i++) {
                            rowMap.put(fieldNames[i], row.getObject(i));
                        }
                        list.add(rowMap);
                    }
                } catch (DBFException e) {
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    DBFUtils.close(reader);
                    try{
                        if (fis != null){
                            fis.close();
                        }
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException | FactoryException | org.opengis.referencing.operation.TransformException e) {
            shp_logger.error("process shp error:{}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            if (iterator != null) {
                try {
                    iterator.close();
                } catch (Exception e) {
                    shp_logger.error("Error closing FeatureIterator: " + e.getMessage());
                }
            }
        }
        return list;
    }

    default String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf(".");
        if (lastIndex != -1) {
            return fileName.substring(lastIndex + 1);
        }
        return "";
    }



}
